/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.facebook.fresco.helper.photoview;

import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.PageSlider;
import ohos.agp.components.StackLayout;
import ohos.agp.components.Text;
import ohos.multimodalinput.event.TouchEvent;

import com.facebook.fresco.helper.ResourceTable;
import com.facebook.fresco.helper.photoview.anim.TransitionCompat;
import com.facebook.fresco.helper.photoview.entity.PhotoInfo;
import com.facebook.fresco.helper.photoview.photodraweeview.OnPhotoTapListener;
import com.facebook.fresco.helper.statusbar.StatusBarCompat;
import com.facebook.fresco.helper.utils.DragCloseHelper;
import com.facebook.fresco.helper.utils.MLog;
import com.facebook.fresco.helper.utils.PhotoConstant;

import java.util.ArrayList;
import java.util.Locale;

/**
 * 图片浏览功能
 *
 * @since 2021-08-06
 */
public class PictureBrowseAbility extends FractionAbility implements PageSlider.PageChangedListener,
    OnPhotoTapListener, Component.LongClickedListener, Component.TouchEventListener {

    /**
     * 图索引
     */
    protected int mPhotoIndex;
    /**
     * 图数
     */
    protected int mPhotoCount;

    /**
     * 集装箱照片
     */
    protected DependentLayout rlPhotoContainer;
    /**
     * 照片底部
     */
    protected DependentLayout rlPhotoBottom;
    /**
     * 容器
     */
    protected StackLayout flContainer;
    /**
     * 照片索引
     */
    protected Text tvPhotoIndex;
    /**
     * 视图ViewPager
     */
    protected MViewPager mViewPager;

    /**
     * 适配器
     */
    protected PictureBrowseAdapter mAdapter;
    /**
     * 图片信息集合
     */
    protected ArrayList<PhotoInfo> mItems;

    /**
     * 过渡兼容
     */
    protected TransitionCompat mTransitionCompat;
    /**
     * 手势操作助手
     */
    protected DragCloseHelper mDragCloseHelper;

    /**
     * 只有一个照片
     */
    protected boolean mPhotoOnlyOne;
    /**
     * 是动画
     */
    protected boolean isAnimation;
    /**
     * 拖近
     */
    protected boolean isDragClose;
    /**
     * 长点击
     */
    protected boolean mLongClick;

    @Override
    public void onStart(Intent intent) {
        StatusBarCompat.translucentStatusBar(this, true);
        super.onStart(intent);
        super.setUIContent(getLayoutResId());
        Intent data = getIntent();
        mItems = data.getSerializableParam(PhotoConstant.PHOTO_LIST_KEY);
        if (mItems == null || mItems.size() == 0) {
            MLog.error("photos data is NULL");
            onBackPressed();
            return;
        }
        mPhotoIndex = data.getIntParam(PhotoConstant.PHOTO_CURRENT_POSITION_KEY, 0);
        isAnimation = data.getBooleanParam(PhotoConstant.PHOTO_ANIMATION_KEY, false);
        mPhotoOnlyOne = data.getBooleanParam(PhotoConstant.PHOTO_ONLY_ONE_KEY, false);
        mLongClick = data.getBooleanParam(PhotoConstant.PHOTO_LONG_CLICK_KEY, true);
        isDragClose = data.getBooleanParam(PhotoConstant.PHOTO_DRAG_CLOSE, false);
        MLog.info("mPhotoIndex = " + mPhotoIndex);
        MLog.info("mLongClick = " + mLongClick);
        MLog.info("mPhotoOnlyOne = " + mPhotoOnlyOne);
        MLog.info("isAnimation = " + isAnimation);
        MLog.info("isDragClose = " + isDragClose);
        setupViews();
        if (isAnimation) {
            mTransitionCompat = new TransitionCompat(PictureBrowseAbility.this);
            mTransitionCompat.setCurrentPosition(mPhotoIndex);
            mTransitionCompat.setParentView(mViewPager);
            mTransitionCompat.startTransition();
        }

        if (isDragClose) {
            setDragClose();
        }
    }

    /**
     * 得到布局res id
     *
     * @return int
     */
    protected int getLayoutResId() {
        return ResourceTable.Layout_ability_picture_browse;
    }

    @Override
    public void onPageSliding(int position, float v1, int i1) {
    }

    @Override
    public void onPageSlideStateChanged(int position) {

    }

    @Override
    public void onPageChosen(int position) {
        if (mPhotoOnlyOne) {
            return;
        }

        mPhotoIndex = position;
        setPhotoIndex();

        if (mTransitionCompat != null && isAnimation) {
            MLog.info("onPageSelected mPhotoIndex = " + mPhotoIndex);
            mTransitionCompat.setCurrentPosition(mPhotoIndex);
        }
    }

    @Override
    protected void onBackPressed() {
        if (mTransitionCompat != null && isAnimation) {
            mTransitionCompat.finishAfterTransition();
        } else {
            terminateAbility();
            setTransitionAnimation(0, 0);
        }
    }

    @Override
    public void onPhotoTap(Component view, float x1, float y1) {
        onBackPressed();
    }

    @Override
    public void onPhotoDrag(Component view, TouchEvent event) {
        onTouchEvent(view, event);
    }

    /**
     * 设置视图
     */
    protected void setupViews() {
        rlPhotoContainer = (DependentLayout) findComponentById(ResourceTable.Id_rl_photo_container);
        flContainer = (StackLayout) findComponentById(ResourceTable.Id_fl_container);
        rlPhotoBottom = (DependentLayout) findComponentById(ResourceTable.Id_rl_photo_bottom);
        tvPhotoIndex = (Text) findComponentById(ResourceTable.Id_tv_photo_count);
        mViewPager = (MViewPager) findComponentById(ResourceTable.Id_vp_picture_browse);
        mViewPager.addPageChangedListener(this);
        mAdapter = new PictureBrowseAdapter(this, mItems, this, mLongClick ? this : null);
        mViewPager.setProvider(mAdapter);
        mPhotoCount = mItems.size();
        setupBottomViews();
        mViewPager.setCurrentPage(mPhotoIndex);
    }

    /**
     * 设置底部视图
     */
    protected void setupBottomViews() {
        if (mPhotoOnlyOne) {
            if (rlPhotoBottom != null) {
                rlPhotoBottom.setVisibility(Component.HIDE);
                tvPhotoIndex.setVisibility(Component.HIDE);
            }
        } else {
            setPhotoIndex();
        }
    }

    /**
     * 组照片指数
     */
    protected void setPhotoIndex() {
        if (tvPhotoIndex != null) {
            tvPhotoIndex.setText(String.format(Locale.getDefault(), "%d/%d", mPhotoIndex + 1, mPhotoCount));
        }
    }

    @Override
    public void onLongClicked(Component component) {
        MLog.info("onLongClick");
    }

    /**
     * 得到项目
     *
     * @return {@link ArrayList}
     */
    public ArrayList<PhotoInfo> getItems() {
        return mItems;
    }

    /**
     * 获取项目
     *
     * @param position 位置
     * @return {@link PhotoInfo}
     */
    public PhotoInfo getItem(int position) {
        if (mItems != null && mItems.size() > 0) {
            return mItems.get(position);
        }
        return null;
    }

    /**
     * 获取当前位置
     *
     * @return int
     */
    public int getCurrentPosition() {
        return mPhotoIndex;
    }

    /**
     * 得到当前的照片信息
     *
     * @return {@link PhotoInfo}
     */
    public PhotoInfo getCurrentPhotoInfo() {
        if (mItems != null && mItems.size() > 0) {
            return mItems.get(mPhotoIndex);
        }
        return null;
    }

    /**
     * 向下拖动关闭
     */
    protected void setDragClose() {
        mDragCloseHelper = new DragCloseHelper(this);
        mDragCloseHelper.setShareElementMode(true);
        mDragCloseHelper.setMinScale(0.2f);
        mDragCloseHelper.setMaxExitY(200);
        mDragCloseHelper.setDragCloseViews(rlPhotoContainer, flContainer, mViewPager);
        mDragCloseHelper.setDragCloseListener(new DragCloseHelper.OnDragCloseListener() {
            @Override
            public boolean intercept() {
                return false;
            }

            @Override
            public void onDragStart() {
                if (rlPhotoBottom != null) {
                    rlPhotoBottom.setVisibility(Component.HIDE);
                }
            }

            @Override
            public void onDragging(float percent) {
            }

            @Override
            public void onDragCancel() {
                if (rlPhotoBottom != null) {
                    rlPhotoBottom.setVisibility(Component.VISIBLE);
                }
            }

            @Override
            public void onDragClose(boolean isShareElementMode) {
                if (isShareElementMode) {
                    onBackPressed();
                }
            }
        });
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        if (mDragCloseHelper != null && mDragCloseHelper.handleEvent(touchEvent)) {
            return true;
        } else {
            return super.onTouchEvent(touchEvent);
        }
    }

    @Override
    protected void onStop() {
        if (mItems != null) {
            mItems = null;
        }

        if (mAdapter != null) {
            mAdapter.recycler();
            mAdapter = null;
        }

        if (mViewPager != null) {
            mViewPager.removePageChangedListener(this);
            mViewPager.setProvider(null);
            mViewPager = null;
        }
        super.onStop();
    }
}
